<?php
// +----------------------------------------------------------------------
// | 有理想的地方，地狱都是天堂。
// +----------------------------------------------------------------------
// | Copyright @ df81.com 版权所有
// +----------------------------------------------------------------------
// | 作者: 南国老符 邮箱：1062129401@qq.com
// +----------------------------------------------------------------------

namespace app\api\controller\v1;
use think\facade\Db;

class Replace {

//站内链接
    private $text;
    public function __toString() {return $this->replace();}//返回替换结果
    public function content($text,$table,$lang){$this->text=$text;$this->table=$table;$this->lang=$lang;}//获取内容给$text
    private function replace(){ //替换函数
        $this->keywords();
		if (empty($this->matches)){
			return $this->text;
		}
		foreach ($this->matches as $k=>$v){
			$this->keywords[$k] = $v['keyword'];
		}
        $pattern = join('|', $this->keywords);
        $pattern ="/((?<!<))($pattern)(?![^<>]*(?:>|<\/a>))/";
        return preg_replace_callback($pattern,array($this, 'callback'),$this->text,5);//替换前5个
    }

    private function callback($matches) { //正则替换回调函数
        global $log; //替换记录，替换过则不在进行相同替换
        if(is_array($matches[2])){
        	return $matches[0];
		}
        $log[] = $matches[2];
		$linkurl = $this->matches[array_search($matches[2], $this->keywords)]['linkurl'];
       	return "<a href=$linkurl>$matches[2]</a>";
    }

    private function keywords(){ //查找关键词
        $kwWhere[] = ['lang','=',$this->lang]; $kwWhere[] = ['signid','=',1]; $kwWhere[] = ['linkurl','<>',''];
        $kwRs = Db::name("keyword")->where($kwWhere)->whereFindInSet('tabledir',$this->table)->order('sequence desc')->limit(200000)->select();
		$m = [];
        foreach ($kwRs as $key => $rs) {
            if (stripos($this->text,$rs['keyword'])){ //内容中包含关键词存入数组
                $m[$rs['id']]['linkurl'] = $rs['linkurl'];
				$m[$rs['id']]['keyword'] = $rs['keyword'];
            }
		}
		krsort($m);//对数组进行逆向排序，最长关键词优先替
        $this->matches = $m;
    }
}